import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';
import { FriendStatus } from '@/app/types/friend';

export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const friendId = params.id;

    const friendship = await prisma.friend.findFirst({
      where: {
        status: FriendStatus.ACCEPTED,
        OR: [
          { userId: userId, friendId: friendId },
          { userId: friendId, friendId: userId },
        ],
      },
    });

    if (!friendship) {
      return NextResponse.json({ error: '你们还不是好友' }, { status: 404 });
    }

    const friendDetail = await prisma.user.findUnique({
      where: { id: friendId },
      select: {
        id: true,
        username: true,
        nickname: true,
        avatar: true,
        bio: true,
      },
    });

    if (!friendDetail) {
      return NextResponse.json({ error: '未找到该用户' }, { status: 404 });
    }

    return NextResponse.json(friendDetail);
  } catch (error) {
    return NextResponse.json({ error: '服务端错误' }, { status: 500 });
  }
}

export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }
    const friendId = params.id;

    const friendship = await prisma.friend.findFirst({
      where: {
        status: FriendStatus.ACCEPTED,
        OR: [
          { userId: userId, friendId: friendId },
          { userId: friendId, friendId: userId },
        ],
      },
    });

    if (!friendship) {
      return NextResponse.json({ error: '你们不是好友，无法删除' }, { status: 404 });
    }

    await prisma.friend.delete({
      where: {
        id: friendship.id,
      },
    });

    return NextResponse.json({ message: '好友已删除' });
  } catch (error) {
    return NextResponse.json({ error: '服务端错误' }, { status: 500 });
  }
}